package com.example.hshiran;


import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.icu.text.LocaleDisplayNames;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

public class Login extends AppCompatActivity {
    private Button button;
    private String path = "https://www.wanandroid.com/user/login";
    private EditText editText1;
    private EditText editText2;
    private Button button2;
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg){
            try{
                if(msg.what == 1)
                {
                    Toast.makeText(Login.this,"登陆成功",Toast.LENGTH_SHORT).show();
                    Uri uri = Uri.parse("https://www.wanandroid.com");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    removeActivity(Login.this);
                }
                else{
                    Toast.makeText(Login.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println("123123123123123");
        editText1 = (EditText) findViewById(R.id.name);
        editText2 = (EditText) findViewById(R.id.pwd);
        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText1.getText().toString();
                String pwd = editText2.getText().toString();
                new Thread() {
                    @Override
                    public void run() {
                        String s = login(name, pwd);
                        try {
                            System.out.println(s);
                            JSONObject object = new JSONObject(s);
                            int errorCode = object.optInt("errorCode");
                            String errorMsg = object.optString("errorMsg");
                            Message msg = new Message();
                            if (errorCode == 0) {
                                msg.what = 1;
                            } else {
                                msg.what = 0;
                            }
                            msg.obj = errorMsg;
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }});
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Login.this, registerActivity.class);
                startActivity(intent);
            }
        });
    }
    long time = 0;
    public void onBackPressed() {
        if(time == 0){
            Toast toast = Toast.makeText(this,"再按一次退出",Toast.LENGTH_SHORT);
            toast.show();
            System.out.println(time);
            time = (new Date()).getTime();
        }else{
            long time2 = (new Date()).getTime();
            if(time2-time<=3000){
                finish();
            }
            else{
                time = 0;
                Toast toast = Toast.makeText(Login.this,"再按一次退出",Toast.LENGTH_SHORT);
                toast.show();
            }
        }

    }

    private String login(String name,String pwd){
        try {
            URL url = new URL(path);
            HttpURLConnection cn = (HttpURLConnection)url.openConnection();
            cn.setRequestMethod("POST");
            cn.setDoOutput(true);
            cn.setUseCaches(false);
            String str = "username="+ URLEncoder.encode(name,"utf-8")+"&password="+URLEncoder.encode(pwd,"utf-8");
            OutputStream outputStream = cn.getOutputStream();
            outputStream.write(str.getBytes());
            outputStream.flush();
            if(cn.getResponseCode()==200){
                InputStream inputStream = cn.getInputStream();
                String s = stream2String(inputStream);
                return s;
            }
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return null;
    }
    private String stream2String(InputStream inputStream){
        BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        try{
            while((line = bf.readLine())!=null){
                stringBuffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }
    public static void removeActivity(Activity activity){
        activity.finish();
    }

}